package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.zmjmall.demo.api.CartService;
import com.zmjmall.demo.api.ProductService;
import com.zmjmall.demo.api.SkuProductService;
import com.zmjmall.demo.enums.ResultEnum;
import com.zmjmall.demo.exception.MallAuthorizeException;
import com.zmjmall.demo.model.Cart;
import com.zmjmall.demo.redis.CartKey;
import com.zmjmall.demo.redis.GoodsKey;
import com.zmjmall.demo.utils.RedisUtil;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.vo.CartVO;
import com.zmjmall.demo.vo.ResultVO;
import com.zmjmall.demo.vo.SkuProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车控制层
 * @author zmj
 * @version 2018/7/4
 */
@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Reference
    private CartService cartService;

    @Reference
    private ProductService productService;

    @Reference
    private SkuProductService skuProductService;


    /**
     * 购物车列表
     * @param userId
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultVO findByUserId(String userId) {
        if(RedisUtil.exists(CartKey.cart, userId)) {
            String s = RedisUtil.get(CartKey.cart, userId);
            List<CartVO> cartVOList = JSONArray.parseArray(s, CartVO.class);
            return ResultVOUtil.success(cartVOList);
        }
        return ResultVOUtil.success(redisCart(userId));
    }

    /**
     * 购物车 增加 减少
     * @param cart
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultVO add(String userId,@Valid Cart cart) {
        cart.setUserId(userId);
        List<String> productListRedis = RedisUtil.getList(GoodsKey.skuProduct);
        if(productListRedis != null) {
            List<String> collect = productListRedis.stream().filter(s -> s.contains(cart.getProductId()))
                    .collect(Collectors.toList());

            if(collect.isEmpty()){
                throw new MallAuthorizeException(ResultEnum.PARAM_ERROR);
            }
            CartVO cartVO = cartService.findByUserIdAndProductId(cart);
            if(cartVO == null) {
                //如果商品在购物车不存在，则加入购物车
                cartService.insert(cart);
            }else{
                cartService.update(cart);
            }
        }else{
            List<SkuProductVO> list = skuProductService.findAll();
            RedisUtil.setList(GoodsKey.skuProduct,list);
        }
        return ResultVOUtil.success(redisCart(cart.getUserId()));
    }

    /**
     * 购物车删除
     */
    @PostMapping("/del")
    @ResponseBody
    public ResultVO del(String userId,@Valid Cart cart) {
        cart.setUserId(userId);
        List<String> productListRedis = RedisUtil.getList(GoodsKey.skuProduct);
        if(productListRedis != null) {
            List<String> collect = productListRedis.stream().filter(s -> s.contains(cart.getProductId()))
                    .collect(Collectors.toList());

            if(collect.isEmpty()){
                throw new MallAuthorizeException(ResultEnum.PARAM_ERROR);
            }
            CartVO cartVO = cartService.findByUserIdAndProductId(cart);
            if(cartVO == null) {
                //如果商品在购物车不存在则抛出异常
                throw new MallAuthorizeException(ResultEnum.PARAM_ERROR);
            }else{
                cartService.delete(cart);
            }
        }else{
            List<SkuProductVO> list = skuProductService.findAll();
            RedisUtil.setList(GoodsKey.skuProduct,list);
        }
        return ResultVOUtil.success(redisCart(cart.getUserId()));
    }

    /**
     * 购物车选中商品
     */
    @PostMapping("/checked")
    @ResponseBody
    public ResultVO checked(String userId,String[] ids) {
        String s = RedisUtil.get(CartKey.cart, userId);
        List<CartVO> cartVOList = JSONArray.parseArray(s, CartVO.class);

        List<String> idsList = Arrays.asList(ids);
        int count = 0;
        for (String id:idsList) {
            for (CartVO cartVO:cartVOList) {
                if(cartVO.getId().equals(id)) {
                    count ++;
                    break;
                }
            }
        }
        if(count != idsList.size()){
            throw new MallAuthorizeException(ResultEnum.PARAM_ERROR);
        }
        cartService.updateChecked(userId,idsList);

        return ResultVOUtil.success(redisCart(userId));
    }

    /**
     * 获取redis 购物车列表
     * @param userId
     * @return
     */
    private List<CartVO> redisCart(String userId) {
        List<CartVO> cartVOList = cartService.findByUserId(userId);
        RedisUtil.set(CartKey.cart,userId,cartVOList);
        return cartVOList;
    }

}
